//
//  NoteViewController.m
//  Ev_Master
//
//  Created by Evan on 2019/6/10.
//  Copyright © 2019 Evan. All rights reserved.
//

#import "NoteViewController.h"
#import "WebViewJavascriptBridge.h"
#import <Masonry.h>
#import <MBProgressHUD.h>
#import "UserCenter.h"
#import "LoginViewController.h"

@interface NoteViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property(nonatomic, strong) NSString *webUrl;
@end

@implementation NoteViewController{
    WKWebView *webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"账户";
    self.webUrl = [NSString stringWithFormat:@"%@%@",WebViewH5Host,@"/shopping/"];
    
    ///设置返回按钮兼容H5
    UIButton *btnBack = [self backBtnImg];
    [btnBack addTarget:self action:@selector(WebGoBack:) forControlEvents:UIControlEventTouchUpInside];
    [self setLeftBarButton:btnBack];
    
    [self webViewJsBri];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self->webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]]];
        });
    });
}



- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]]];
}

-(void)dealloc{
    [DKProgressHUD dismiss];
}

#pragma mark - js注入刷新

-(void)webViewJsBri{
    ///初始化是注入cookie
    NSString *strToken = [NSString stringWithFormat:@"token=%@",[UserCenter shareCenter].authToken];
    
    NSString * eString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)[UserCenter shareCenter].user.member.username,NULL,NULL,kCFStringEncodingUTF8));
    NSString *strUserName = [NSString stringWithFormat: @"username=%@",eString];
    
    NSString *str = [[UserCenter shareCenter].user.member mj_JSONString];
    //        str = [str stringByReplacingOccurrencesOfString:@"{" withString:@""];
    //        str = [str stringByReplacingOccurrencesOfString:@"}" withString:@""];
    NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)str,NULL,NULL,kCFStringEncodingUTF8));
    //    str = [str stringByReplacingOccurrencesOfString:@"\"" withString:@"%22"];
    NSString * strUserInfo = [NSString stringWithFormat:@"userinfo=%@",encodedString];
    
    NSString *cookie = [NSString stringWithFormat:@"document.cookie='%@';document.cookie='%@';document.cookie='%@';",strToken,strUserName,strUserInfo];
    if([UserCenter shareCenter].user.spottradinguser != nil){
        NSString *str2 = [[UserCenter shareCenter].user.spottradinguser mj_JSONString];
        str2 = [str2 stringByReplacingOccurrencesOfString:@"\"" withString:@"%22"];
        NSString * strUserspottradinguser = [NSString stringWithFormat:@"spottradinguser=%@",str2];
        cookie = [NSString stringWithFormat:@"%@document.cookie='%@';",cookie,strUserspottradinguser];
    }
    
    WKUserContentController* userContentController = WKUserContentController.new;
    WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource: cookie injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    
    [userContentController addScriptMessageHandler:self name:@"APPJS"];
    
    [userContentController addUserScript:cookieScript];
    WKWebViewConfiguration* webViewConfig = WKWebViewConfiguration.new;
    webViewConfig.userContentController = userContentController;
    
    
    webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:webViewConfig];
    [self.view removeFromSuperview];
    [self.view addSubview:webView];
    [webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(self.mas_topLayoutGuide);
        make.height.offset(KScreenHeight - KSHeight_NavBar - KSHeight_TabBar);
    }];
    
    
    webView.UIDelegate = self;
    webView.navigationDelegate = self;
    
    
    //    NSString *path = [[NSBundle mainBundle] pathForResource:@"Index.html" ofType:nil];
    //    NSString *htmlString = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    //    //加载本地html文件
    //    [webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
    //加载域名地址
    
    ///刷新WebView
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginIfSuccess) name:Notification_login_ok_notice object:nil];
}


#pragma mark - 重复登录后，刷新用户

-(void)loginIfSuccess{
    [self webViewJsBri];
}

#pragma mark - Navigation Back Click

- (void)WebGoBack:(UIButton*)sender{
    WKBackForwardList *list=  [webView backForwardList];
    NSArray<WKBackForwardListItem*> *listitem = list.backList;
    if(listitem.count > 0){
        WKBackForwardListItem *item = listitem.lastObject;
        NSLog(@"后退历史：%@",item.title);
        [webView goToBackForwardListItem:item];
    }
    else{
        [[UserCenter shareCenter]refreshProfiles:^(modelUserInfo *profile) {
            [self goBack:nil];
        }];
    }
}

#pragma mark - JS回调本地方法
//OC在JS调用方法做的处理
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSLog(@"JS 调用了 %@ 方法，传回参数 %@",message.name,message.body);
    if ([message.name  isEqualToString: @"APPJS"] && [message.body isEqualToString:@"shouldLogin"]) {
        [[UserCenter shareCenter] clearUserState];
        LoginViewController *vc = [[LoginViewController alloc]init];
        [self.navigationController  presentViewController:vc animated:YES completion:nil];
    }
}


#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
        [DKProgressHUD showLoading];
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"加载完成：%@",[webView.URL absoluteString]);
    [DKProgressHUD dismiss];
    //获取hH5的cookie
    NSString *js = @"document.title";
    [webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"获取H5cookie：%@",response);
        self.navigationController.title = (NSString*)response;
    }];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationActionPolicyCancel);
}
#pragma mark - WKUIDelegate
// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    return [[WKWebView alloc]init];
}
// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
    completionHandler(@"http");
}
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    completionHandler(YES);
}
// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    NSLog(@"%@",message);
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the text mode to show only text.
    hud.mode = MBProgressHUDModeCustomView;
    hud.label.text = NSLocalizedString(message, @"提示");
    // Move to bottm center.
    hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
    
    [hud hideAnimated:YES afterDelay:3.f];
    completionHandler();
}

@end
